package com.cainiao.filter;

import com.cainiao.utils.JwtUtils;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
@Slf4j
@WebFilter("/*")
public class TokenFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request= (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse)servletResponse;
        //获取请求路径
        String requestURl =request.getRequestURL().toString(); ;
        //判断是否为登录请求
        if(requestURl.contains("/login")){
            filterChain.doFilter(request,response);
            return;
        }
        //获取请求头中的token
        String token = request.getHeader("token");
        //判断是否为空
        if(token==null||token.equals("")){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        //验证token是否正确
        try{
            JwtUtils.parseJWT(token);
        }catch (Exception e){
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return;
        }
        log.info("请求路径：{}",requestURl);
        filterChain.doFilter(request,response);
    }
}
